# -*- coding: utf-8 -*-
import asyncio
import aiofiles
import pandas as pd
import os
import sys
from aiofiles import os as aio_os
from datetime import datetime, timedelta
from io import BytesIO

USER_AGENT = (
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
)

def make_constant_retry_policy(interval: float):
    def get_interval(_retry_count: int, _total_retry_count: int):
        return interval
    return get_interval


def make_linear_retry_policy(start_interval: float, interval_step: float, max_interval: float):
    def get_interval(retry_count: int, _total_retry_count: int):
        return min(
            start_interval + (retry_count - 1) * interval_step,
            max_interval
        )
    return get_interval

def get_yesterday(input_date: str) -> str:
    """计算输入日期的前一天
    Args:
        input_date: 格式为"%Y-%m-%d"的日期字符串
    Returns:
        格式相同的昨天日期字符串
    """
    try:
        dt_obj = datetime.strptime(input_date, "%Y-%m-%d-%H-%M")
        yesterday = dt_obj - timedelta(days=1)
        return yesterday.strftime("%Y-%m-%d-%H-%M")
    except ValueError as e:
        raise ValueError(f"输入格式必须为YYYY-MM-DD-HH-MM，当前输入：{input_date}") from e

async def async_write_df_to_excel(df, file_path, sheet_name, mode='a'):
    """异步写入DataFrame到Excel文件，支持追加模式"""
    try:
        output = BytesIO()
        
        if mode == 'w':
            with pd.ExcelWriter(output, engine='openpyxl') as writer:
                df.to_excel(writer, sheet_name=sheet_name, index=False)
        else:
            try:
                # 异步读取现有文件
                async with aiofiles.open(file_path, 'rb') as f:
                    content = await f.read()
                existing_data = pd.read_excel(BytesIO(content), sheet_name=None)
                
                with pd.ExcelWriter(output, engine='openpyxl') as writer:
                    for name, data in existing_data.items():
                        if name == sheet_name:
                            # 合并新旧数据
                            combined_df = pd.concat([data, df], ignore_index=True)
                            combined_df.to_excel(writer, sheet_name=name, index=False)
                        else:
                            data.to_excel(writer, sheet_name=name, index=False)
                    if sheet_name not in existing_data:
                        df.to_excel(writer, sheet_name=sheet_name, index=False)
            except FileNotFoundError:
                with pd.ExcelWriter(output, engine='openpyxl') as writer:
                    df.to_excel(writer, sheet_name=sheet_name, index=False)
        
        # 异步写入文件
        async with aiofiles.open(file_path, 'wb') as f:
            await f.write(output.getvalue())
        return True
    except Exception as e:
        print(f"异步写入失败: {str(e)}")
        return False
    
async def async_ensure_path_exists(path):
    """异步确保目录存在，不存在则递归创建"""
    try:
        if not await aio_os.path.exists(path):
            await aio_os.makedirs(path, mode=0o755)
            print(f"异步创建目录: {path}")
        else:
            print(f"目录已存在: {path}")
    except Exception as e:
        print(f"异步操作失败: {e}")

def which_system():
    if sys.platform.startswith('linux'):
        return 'linux'
    elif sys.platform == 'win32':
        return 'windows'
    else:
        print("其他操作系统")
        return 'unknown'

class DualLogger:
    _instance = None
    
    def __new__(cls, filename):
        if not cls._instance:
            cls._instance = super().__new__(cls)
            cls._instance.terminal = sys.stdout
            cls._instance.logfile = open(filename, 'a', encoding='utf-8')
        return cls._instance
        
    def write(self, message):
        self.terminal.write(message)
        if message.strip():
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.logfile.write(f"[{timestamp}] {message}\n")
            
    def flush(self):
        self.terminal.flush()
        self.logfile.flush()

# 使用示例
if which_system() == 'windows':
    logger = DualLogger('app.log')
elif which_system() == 'linux':
    logger = DualLogger('/home/data/blivedm/app.log')
sys.stdout = logger
sys.stderr = logger